package com.anlogic.sdk.bootimage.internal;

import com.anlogic.sdk.bootimage.model.BootGenModel;
import com.anlogic.sdk.utils.ICommandLauncher;
import com.anlogic.sdk.utils.LogUtils;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.apache.logging.log4j.Logger;
import org.eclipse.core.resources.WorkspaceJob;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;


public class BootgenJob extends WorkspaceJob {
	private static Logger logger = LogUtils.getLogger(BootgenJob.class);

	private ICommandLauncher launcher;

	private File pwd;

	private BootGenModel model;

	public BootgenJob(String name, BootGenModel model, ICommandLauncher launcher) {
		super(name);
		this.launcher = launcher;
		this.model = model;
		String bifFile = model.getBifFile();
		if (bifFile.endsWith(".bif")) {
			String bifPath = (new Path(bifFile)).removeLastSegments(1).toPortableString();
			this.pwd = new File(bifPath);
		}
	}

	private void createBifFile() {
		try {
			Path path = new Path(this.model.getBifFile());
			File newFile = new File(path.toOSString());
			newFile.getParentFile().mkdirs();
			newFile.createNewFile();
			BufferedWriter writer = new BufferedWriter(new FileWriter(newFile));
			try {
				writer.write(this.model.getBifContent());
			} finally {
				writer.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
		NullProgressMonitor nullProgressMonitor;
		logger.info("Create boot image start...");
		File bifFile = new File(this.model.getBifFile());
		if (!bifFile.exists()) {
			logger.info("Creating new bif file {}", this.model.getBifFile());
			monitor.beginTask("Creating new bif file", -1);
			createBifFile();
		} else if (this.model.isOverwriteBif()) {
			logger.info("Overwriting existing bif file {}", this.model.getBifFile());
			monitor.beginTask("Overwriting existing bif file", -1);
			createBifFile();
		}
		monitor.beginTask("Invoking Bootgen", -1);
		this.launcher.asyncLaunch(this.model.getCommand(), this.pwd, null);
		while (!this.launcher.hasTerminated()) {
			try {
				Thread.sleep(500L);
			} catch (InterruptedException e) {
				logger.error("Unexpected error occurred {}", e.getMessage());
			}
			if (monitor.isCanceled())
				this.launcher.terminate();
		}
	    if (monitor.isCanceled()) {
	    	nullProgressMonitor = new NullProgressMonitor();
	    	nullProgressMonitor.done();
	    }
		logger.info("Create boot image done");
		return Status.OK_STATUS;
	}
}
